const express = require('express')
const router = express.Router()
const multer = require('multer')
const filePath = './uploads/'
const path = require('path')
const menuModel = require('../../db/menu')

const upload = multer({storage: multer.diskStorage({
    destination(req, file, cb) {
        cb(null, filePath)
    },
    filename(req, file, cb) {
        let suffix = path.extname(file.originalname)
        let filename = +new Date() + Math.floor(Math.random() * 899999) + 100000 + suffix
        cb(null, filename)
    }
})})

/*
添加商品：
    方式 - post
    路径 - /admin/api/menus/add
    请求主体：
        name: 商品名称,
        price: 价格,
        imgpath: 图片地址,
        specifications: 规格,
        kind: 种类,
        enable: 是否可购买
    响应 - 成功或失败
*/
router.post('/add', upload.single('imgpath'), (req, res) => {
    // 接收数据
    let {name, price, spec: specifications, kind, catname} = req.body
    // console.log(req.body);
    // 获取图片路径
    // console.log(req.file)
    let imgpath = req.file.path.replace(/\\/g, '/')
    // 存入数据库
    menuModel.findOne({name}, (err, docs) => {
        if(err) {
            throw new Error(err)
        }
        if(docs) {
            res.json({
                error_code: 1,
                msg: '商品已经存在！'
            })
            return
        }
        menuModel.insertMany({
            name, 
            price, 
            catname,
            specifications: specifications.join('====='), 
            kind: kind.join('====='),
            imgpath
        }, (err, docs) => {
            if(err) {
                throw new Error(err)
            }
            res.json({
                error_code: 0,
                msg: '商品添加成功！'
            })
        })
    })
})

module.exports = router